function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}
/*
 * MyStatus 
 */

var MyStatus = function()
{
	this._this	= this;
	//this._url = "../library/State.php";
	this._url = MyStatus.url;
};
//MyStatus.url = "http://localhost/~james/riskcuhk/logic.php";
MyStatus.url = "../library/State.php";

MyStatus.updateInterface = function(state)
{
	printf("updateInterface = " + state);
	//$('#coveringDiv').style.display = 'none';
	//
	var coveringDiv = $('#coveringDiv');

	if (state == 'Watching')
	{
		coveringDiv.css("display", "block");
	}
	else if (state == 'PlaceArmy')
	{
		coveringDiv.css("display", "none");

	}
	else if (state == 'Attack')
	{
		coveringDiv.css("display", "none");

	}
	else if (state == 'Fortify')
	{
		coveringDiv.css("display", "none");

	}
	else
	alert('MyStatus.updateInterface has unexpected state');
}

MyStatus.prototype = {
	ready: function()
	{
		var data = "name=player1";
		data += "&status=ready";
		data += "&action=execute&json=1";

		printf(this._url+"?"+data);;

		$.ajax({
			url: this._url,
			data: data,
			dataType: 'json',
			success: this.readySuccess
		});
	},

	readySuccess: function(data, status)
	{
		printf("");
		printf("sent ready");
		printf(data, status);


		// should get the data 
		//var parsedPlayerJSON = PlayerModel.parsePlayer(data.user_info);
		//var playerModel = new PlayerModel(parsedPlayerJSON);

		var playerModel = new PlayerModel(playersJSON);
		//var playerModel = new PlayerModel(playersJSON);
		playerView = new PlayerView
		(
			playerModel,
			new PlayerController(playerModel), 
			{ playerStatusDiv : document.getElementById('playerStatusDiv') }
		);

		playerView.show();

		//if ( ! data.map_status ) data.map_status = array();
		//var areaModel = new AreaModel(document.getElementsByTagName('area'), data.map_status);
		var areaModel = new AreaModel(document.getElementsByTagName('area'));
		areaView = new AreaView
		(
			areaModel,
			new AreaController(areaModel),
			{
				areaDiv: document.getElementById('areaDiv')
			}	
		);
		areaView.show();

		var stateModel = new StateModel(StateModel.getByRequest());
		stateView = new StateView
		(	
			stateModel,
			new StateController(stateModel),
			{
				myStatusDiv: document.getElementById('myStatusDiv'),
			}
		);

		stateView.show();

		/*
		 var myStatus = new MyStatus();
		 printf("sending watching message");
		 myStatus.watching();

		 */
		MyStatus.updateInterface(playerModel.getMyPlayingStatus());
		//this.destroy();
	},


	watching: function()
	{
		var data = "name=player1";
		data += "&status=watching";
		data += "&json=1&action=execute";

		printf(this._url+"?"+data);;

		$.ajax({
			url: this._url,
			data: data,
			dataType: 'json',
			success: this.watchingSuccess
		});

	},

	watchingSuccess: function(data, status)
	{
		printf(data);
		printf("watchingSuccess");

		//MyStatus.updateInterface(playerModel.getMyPlayingStatus());
	},

	placed: function(areaTitle, amount)
	{
		var _this = this;
		var data = "deploy_on=" + areaTitle;
		data += "&action=execute&json=1";

		printf(this._url+"?"+data);;

		$.ajax({
			url: this._url,
			data: data,
			dataType: 'json',
			success: function(data, status) 
			{	_this.placedSuccess(data, status);  }
		});
	},

	placedSuccess: function(data, status)
	{
		printf("placed success");

		var playerModel = new PlayerModel(playersJSON);
		//var playerModel = new PlayerModel(playersJSON);
		playerView = new PlayerView
		(
			playerModel,
			new PlayerController(playerModel), 
			{ playerStatusDiv : document.getElementById('playerStatusDiv') }
		);

		playerView.show();

		/*
		 var areaModel = new AreaModel(document.getElementsByTagName('area'));
		 var areaView = new AreaView
		 (
			 areaModel,
			 new AreaController(areaModel),
			 {
				 areaDiv: document.getElementById('areaDiv')
			 }	
		 );
		 areaView.show();
		 */
		areaView._controller.updateModel();
		areaView.updateView();

		var stateModel = new StateModel(StateModel.getByRequest());
		stateView = new StateView
		(	
			stateModel,
			new StateController(stateModel),
			{
				myStatusDiv: document.getElementById('myStatusDiv'),
			}
		);

		stateView.show();

	}
};

MyStatus.firstDeploy = 1;

MyStatus.placed = function(areaTitle, amount)
{
	var data = "deploy_on=" + areaTitle;
	data += "&action=execute&json=1";

	printf(MyStatus.url+"?"+data);;

	if (MyStatus.firstDeploy)
	{
		$.ajax({
			url: MyStatus.url,
			data: data,
			dataType: 'json',
			//success: myStatus.readySuccess
			success: function(data, status)
			{
				myStatus.readySuccess(data);
				/*
				 printf("finished placing with data, status");
				 printf(data);
				 */
			}
		});
	}
	MyStatus.firstDeploy = 1;

	/*
	 $.getJSON(MyStatus.url, data)
	 {

	 }
	 */
};




/*
 * State MVC
 */

var StateModel = function(states)
{
	this._states = states;
	this.selected = new Event(this);
};

StateModel.getByRequest = function()
{
	var state = $.ajax({
		url: '../library/State.php',
		data: 'action=execute&json=1',
		dataType: 'json',
		async: false /*,
		success: function(state) {
			printf(state);
		}*/
	   }).responseText;
	   return new StateModel(eval('(' + state + ')'));
   };

   StateModel.prototype = {
	   getStates: function()
	   {
		   return this._states;
	   }
   };

   var StateController = function(model)
   {
	   this._model = model;
   };

   StateController.prototype = {
	   changeState : function(e, _this)
	   {
		   var state = e.currentTarget.innerHTML;
		   var playerModel = playerView._model;
		   //printf(playerModel);
		   playerModel.getMe().playerState = state;
		   //printf(playerModel.getMe());
		   playerView.show();
		   MyStatus.updateInterface(playerModel.getMyPlayingStatus());

	   }
   };

   var StateView = function(model, controller, elements)
   {
	   this._model 		= model;
	   this._controller 	= controller;
	   this._elements 		= elements;

   };

   StateView.prototype = {
	   show: function()
	   {
		   var anchors = this._elements.myStatusDiv.getElementsByTagName('a');
		   var _this	= this;

		   for (var i = 0; i < anchors.length; i++)
		   {
			   var anchor = anchors[i];
			   anchor.addEventListener('click', function(e){
				   _this._controller.changeState(e, _this);
			   }, false);
		   }
	   },

   }




   /*
	* Area MVC
	*/

   var AreaModel = function(areas, areasToBeParsed)
   {
	   this._areas = this.initAreas(areas);
	   //this._areas = this.parseMap(this._areas, areasToBeParsed);
	   this._areaIndexByTitle = '';//new Hash();

	   this.armyAdded = new Event(this);
   }

   AreaModel.prototype = {
	   parseMap: function(areas, areasToBeParsed)
	   {
		   for (var i = 0; i < areasToBeParsed.length; i++)
		   {
			   var real = areasToBeParsed[i];

		   }

		   printf("this.fake");
		   for (var fake in this._areaIndexByTitle)
		   {
			   printf(fake);
		   }


		   return areas;
	   },
	   initAreas: function(areas)
	   {
		   var areasJSON = [];
		   var buttonsJSON = [];
		   var _this = this;
		   $('#armyDiv > *').remove();
		   for (var i = 0; i < areas.length; i++)
		   {
			   var area = areas[i];
			   if (area.title.search('Div') == -1)
			   {
				   // not found
				   var buttonDiv = area.title.replace(/ /ig, "_");
				   buttonDiv	= "Div_" + buttonDiv;
				   var areaJSON = {
					   "title"			: area.title,
					   "id"			: area.id,
					   "buttonDiv"		: buttonDiv,
					   "element"		: area,
					   "numberOfArmies": 0
				   };

				   //eval("areasJSON['" + area.title + "'] =  areaJSON;");
				   areasJSON.push(areaJSON);
				   //var toEval = "_this._areaIndexByTitle['" + area.title.toLowerCase() + "'] = " + (areasJSON.length - 1) + ";";
				   //_this._areaIndexByTitle.setItem(area.title, i);
				   //printf(toEval);
				   //eval(toEval);
				   //_this._areaIndexByTitle["\"" + area.title + "\""] = areasJSON.length - 1;
			   }
			   else
			   {
				   var str = area + " ";

				   var pattern = /^\d+/;
				   pattern = /^\d+,\d+/;
				   var size = area.coords.match(pattern).toString().split(',');

				   var offsetTop = $('#index').offset().top + parseInt(size[1]);
				   var offsetLeft = $('#index').offset().left + parseInt(size[0]);

				   var div = $('<div>');
				   div.css("display", "block")
				   .css("position", "absolute")
				   .css("left", offsetLeft)
				   .css("top", offsetTop)
				   .css("width", 32)
				   .css("height", 32)
				   .css("backgroundRepeat","no-repeat")
				   .css("background-align","center")
				   .css("line-height","32px")
				   .css("text-align","center");
				   div.attr('id', area.title);

				   div.click(function(e)
				   {
					   _this.clickParent(e);
				   });

				   div.hover(
					   function(e)
					   {
						   _this.hoverInParent(e);
					   },
					   function(e)
					   {
						   _this.hoverOutParent(e);
					   }
				   );

				   div.appendTo($('#armyDiv'));
			   }

		   }

		   for(var k=0;k<areasJSON.length;k++){
			   var areaJSON = areasJSON[k];
			   var noOfArmies = areaJSON.numberOfArmies;
			   //if(noOfArmies > 0){
				   var buttonDivID = areaJSON.buttonDiv;
				   showArmy(buttonDivID,1,noOfArmies);
				   //}
			   }

			   printf("showing areasJSON");
			   printf(areasJSON);
			   return areasJSON;
		   },
		   findParentTitle: function(e)
		   {
			   var currentTarget = e.currentTarget;
			   var parentTitle = currentTarget.id.substring(4);
			   parentTitle = parentTitle.replace(/_/i, " ");
			   return parentTitle;
		   },
		   clickParent: function(e)
		   {
			   var parentTitle = this.findParentTitle(e);
			   this.addArmy(parentTitle, 1);
		   },
		   hoverInParent: function(e)
		   {
			   var parentTitle = this.findParentTitle(e);
			   var selectedArea = this.findSelectedAreaByTitle(parentTitle);
			   //printf("act to be mouseover " + selectedArea.id);
			   $('#'+selectedArea.id).mouseover();
		   },
		   hoverOutParent: function(e)
		   {
			   var parentTitle = this.findParentTitle(e);
			   var selectedArea = this.findSelectedAreaByTitle(parentTitle);
			   //printf("act to be mouseout " + selectedArea.id);
			   $('#'+selectedArea.id).mouseout();
		   },
		   getAreas: function()
		   {
			   return this._areas;
		   },
		   getArmiesForArea: function(area)
		   {
			   //return this.area.a
		   },
		   findSelectedAreaByTitle: function(areaTitle)
		   {
			   var selectedArea;
			   for (var i = 0; i< this._areas.length; i++)
			   {
				   var area = this._areas[i];
				   if (area.title == areaTitle)
				   {
					   selectedArea = area;
					   break;
				   }
			   }
			   return selectedArea;
		   },
		   addArmy: function(areaTitle, amount)
		   {
			   var selectedArea = this.findSelectedAreaByTitle(areaTitle);
			   //printf(selectedArea);
			   selectedArea.numberOfArmies += amount;
			   printf(selectedArea.title + ":" + selectedArea.numberOfArmies);
			   printf(selectedArea);
			   printf("id: " + selectedArea.element.id);

			   //var myStatus = new MyStatus();
			   printf("sending placed army message");

			   myStatus.placed(areaTitle, amount);
			   //MyStatus.updateInterface(player
		   }
	   };


	   var AreaController = function(model)
	   {
		   this._model = model;
	   };

	   AreaController.prototype = {
		   updateModel : function(model)
		   {
			   if ( ! model)
			   this._model = model;
			   //this.updateView();
		   },
		   addArmy: function(e, amount)
		   {
			   //printf(e.currentTarget);
			   var title = e.currentTarget.title;
			   this._model.addArmy(title, amount);
		   }
	   };

	   var AreaView = function(model, controller, elements)
	   {
		   this._model = model;
		   this._controller = controller;
		   this._elements 	= elements;

		   var _this = this;
	   };

	   AreaView.prototype = {
		   show: function()
		   {
			   //areaDiv.innerHTML = this._model.getAreas();
			   //printf(this._model.getAreas());
			   var _this = this;
			   var areas = _this._model.getAreas();

			   for (var i = 0; i < areas.length; i++)
			   {
				   var area = areas[i];

				   area.element.addEventListener("click", function(e)
				   {
					   _this._controller.addArmy(e, 1);
				   }, false);

				   /*
					printf("this._model");
					printf($(this._model));
					$(area).delegate("#" + area.id, "click", function()
					{
						printf(this);
					});
					*/
			   }
		   },
		   updateView: function()
		   {
			   printf("update View");
			   var _this = this;

			   var areas = _this._model.getAreas();

			   for (var i = 0; i < areas.length; i++)
			   {
				   var area = areas[i];
				   showArmy(area.buttonDiv,1,area.numberOfArmies);
			   }
		   }
	   };















	   /*
		* Player Model
		**/
	   var PlayerModel = function(players)
	   {
		   this._players = players;
		   this._armies = 0;

		   this.armyAdded = new Event(this);
	   };

	   PlayerModel.parsePlayer = function(players)
	   {
		   var cookie = readCookie("session_key");
		   printf("my session id: " +  cookie);
		   for (var i = 0; i < players.length; i++)
		   {
			   var player = players[i];

			   player.isYou = player.session_key == cookie ? 1 : 0;
			   if ( player.turn == 1 )
			   {
				   if (player.status == "DEPLOYMENT")
				   {
					   player.playerState = "PlaceArmy";
				   }
				   else 
				   player.playerState = "Watching";
			   }
			   else
			   player.playerState = "Watching";
		   }
		   printf("parsed");
		   printf(players);

		   return players;
	   };

	   PlayerModel.prototype = {
		   getMe : function()
		   {
			   for (var i = 0; i < this._players.length; i++)
			   {
				   var player = this._players[i];
				   if (player.isYou == 1)
				   return player;
			   }
			   alert('You are not playing');
		   },
		   getMyPlayingStatus : function()
		   {
			   var me = this.getMe();
			   return me.playerState;
		   },
		   getPlayers : function()
		   {
			   return this._players;
		   },
		   addArmy: function(land)
		   {
			   this._armies++;
			   this.armyAdded.notify();
		   },
		   getByRequest: function()
		   {
		   }
	   };

	   /*
		* Player View
		**/
	   var PlayerView = function(model, controller, elements)
	   {
		   this._model = model;
		   this._controller = controller;
		   this._elements = elements;

		   var _this = this;

		   //this._model.armyAdded.attach(
		   };

		   PlayerView.prototype = {
			   show: function()
			   {
				   var players = this._model.getPlayers()
				   //printf("showing playersJSON");
				   //printf(players);

				   var html = '';

				   for (var i = 0; i < players.length; i++)
				   {
					   var player = players[i];
					   //printf(player);
					   html +=
					   "		<b>" + player.username + (player.isYou ? ' (you)' : '') + "</b>" + 
					   "		<table>" +
					   "			<tr>" +
					   "			<td id='playerStatusArmies'>armies</td><td>" + player.numberOfArmies + "</td>" +
					   "			<td>lands</td><td>" + player.numberOfLands + "</td>" +
					   "			<td>cards</td><td>" + player.numberOfCards +"</td>" +
					   "			</tr>" +
					   "			<tr>" +
					   "			<td colspan=3 class='playerState'>" + player.playerState + "</td>" + 
					   "			</tr>" + 
					   "			<tr>" +
					   "			<td colspan=3 class='ownedLands'>owned lands</td>" + 
					   "			</tr>" + 
					   "		</table>";
				   }

				   this._elements.playerStatusDiv.innerHTML = html;

				   // areas add event
				   /*
					var areas = this._elements.areas;
					for (var i = 0; i < areas.length; i++)
					{
						var area = areas[i];
						printf(i + " "  + area.title);

						area.addEventListener("click", 
						display(i, area.title),
						false);
					}*/
			   }
		   };

		   var display = function(i, title)
		   {
			   printf(i + " "  + title);
		   };


		   /*
			* Player Controller
			**/
		   var PlayerController = function(model)
		   {
			   this._model = model;
		   };

		   PlayerController.prototype = {
			   addArmy: function()
			   {
				   var army = printf("added:");
				   if (army)
				   this._model.addArmy(army);
			   }
		   };


		   /*
			* Event Object
			*/
		   var Event = function (sender) {
			   this._sender = sender;
			   this._listeners = [];
		   };

		   Event.prototype = {
			   attach : function (listener) {
				   this._listeners.push(listener);
			   },
			   notify : function (args) {
				   for (var i = 0; i < this._listeners.length; i++) {
					   this._listeners[i](this._sender, args);
				   }
			   }
		   };

		   var self = this;
		   var playerView;
		   var stateView;
		   var areaView;
		   var myStatus;
		   window.onload = function()
		   {
			   var img = window.document.getElementById('index');
			   img.className = "mapper noborder";

			   myStatus = new MyStatus();
			   printf("sending ready message");
			   var response = eval('(' + myStatus.ready() + ')');

		   };
